package com.lotter.api.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.lotter.api.service.ImageUploadService;
import com.lotter.common.context.YcContext;
import com.lotter.common.util.StringUtil;

//图片上传  不加权限
@Controller
@RequestMapping(value="/website/image")
public class ImageUploadController extends BaseController{
	
	@Autowired
	private ImageUploadService imageUploadService;
	
	/**
	 * 上传图片
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/upload",method =RequestMethod.POST)
	public  Map<String,Object>  upload(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		int fileCount = multipartRequest.getFileMap().size();
		if (fileCount < 1) {
			return ajaxLotterStage("上传数量大于1");        
		}
		MultipartFile multipartFile = multipartRequest.getFile("file");
		if(multipartFile.getSize() > 5000000){
			return ajaxLotterStage("文件大于5m");
		}
		String fileName = multipartFile.getOriginalFilename();
		String SuffixName =  fileName.substring(fileName.lastIndexOf("."));
		String imgExt = ".jpg|.jpeg|.png|.bmp|.GIF|.JPG|.PNG|.JPEG";
		if(imgExt .indexOf(SuffixName) == -1){
			return ajaxLotterStage("上传格式不正确");
		}
		String path = serverPathUtil(request);
		Map<String,Object> result = new HashMap<String, Object>();
		try {
			String inagePath = imageUploadService.saveImagePartners(multipartFile,path);
			if(StringUtil.isNotBlank(inagePath)){
				result.put("inagePath", inagePath);
			}else{
				return ajaxLotterServer("上传失败");
			}
		} catch (Exception e) {
			logger.error("图片上传错误");
			return ajaxLotterServer("服务器异常,请联系管理员");
		} 
		return ajaxLotterSuccess(result);
	}
	
	/**
	 * 获取上传路径
	 * @param request
	 * @return
	 */
	private static String serverPathUtil(HttpServletRequest request){
		String serverPath = request.getServletContext().getRealPath(YcContext.Slash);
		serverPath =StringUtil.replace(serverPath, "\\", YcContext.Slash);
		if(serverPath.lastIndexOf(YcContext.Slash)==serverPath.length()-1){
			serverPath =serverPath.substring(0,serverPath.length()-1);
		}
		serverPath = serverPath.substring(0, serverPath.lastIndexOf(YcContext.Slash));
		serverPath+=YcContext.Slash ;
		serverPath+=YcContext.IMAGE_PATH ;
		return serverPath;
	}
	
	
	public static void main(String[] args) {
		String temp ="E:/apache-tomcat-8081/webapps/LotterGodApi/" ;
		System.out.println(temp.substring(0, temp.lastIndexOf("/"))  );
	}

}
